
const { queryInspectionList, deleteInspectionById, getTemplateDropdownList } = require('../../api/inspection')
const {
  to,
  openLoading,
  closeLoading,
  routeWithToken
} = getApp()
const {
  getUserBaseInformation
} = require('../../utils/strorage')
Page({
  data: {
    loadingType: '',
    dataList: [],
    templateOptions: [],
    pagination: {
      page: 1,
      limit: 10
    },
    searchData: {},
    total: 0
  },

  onLoad() {
    this.resetData()
    this.getInspectionList()
    this.getTemplateOptions()
  },

  async getTemplateOptions() {
    const [err, data] = await to(getTemplateDropdownList());

    if (!err) {
      this.setData({
        templateOptions: data
      })
      return Promise.resolve()
    }
    return Promise.reject(err)
  },
  resetData() {
    this.setData({
      total: 0,
      pagination: {
        page: 1,
        limit: 10
      },
      dataList: [],
      loadingType: ''
    })
  },

  onSearchChange(event) {
    const data = event.detail;
    this.setData({
      searchData: data
    })
    this.resetData()
    this.getInspectionList()
  },

  async getInspectionList(openL = true) {
    openL && openLoading()
    const userInfo = getUserBaseInformation();
    const [err, data] = await to(queryInspectionList({
      userId: userInfo.userId,
      ...this.data.searchData
    }))
    closeLoading()
    if (!err) {
      const {
        dataList
      } = this.data
      this.setData({
        dataList: dataList.concat(data.dataList),
        total: data.total
      })

      if (data.total === 0) {
        this.setData({
          loadingType: 'empty'
        })
        return
      }

      if (this.data.dataList.length >= data.total) {
        this.setData({
          loadingType: 'end'
        })
      }
    }
  },

  handleScrolltolower() {
    const {
      total,
      pagination,
      dataList
    } = this.data

    if (dataList.length < total) {
      let page = pagination.page;
      page++
      this.setData({
        loadingType: 'loading',
        ['pagination.page']: page
      })
      this.getInspectionList(false)
    }
  },
  handleEdit(event) {
    routeWithToken('./inspection-form/index?type=edit&id=' + event.detail.inspectionId)
  },
  handleToAddInspection() {
    routeWithToken('./inspection-form/index?type=add')
  },

  handleToRoute(event) {
    routeWithToken('./inspection-form/index?type=review&id=' + event.detail.inspectionId)
  },

  handleDelete(event) {
    wx.showModal({
      content: '是否删除?',
      title: '提示',
      success: (res) => {
        if (res.confirm) {
          this.deleteData(event.detail)
        }
      }
    })
  },

  async deleteData(param) {
    const params = {
      id: param.inspectionId
    }
    openLoading()
    const [err] = await to(deleteInspectionById(params))
    closeLoading()
    if (!err) {
      this.resetData()
      this.getInspectionList()
    }
  },
})